#!/usr/bin/env python
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

def _include_sqlalchemy(obj):
    for module in sqlalchemy, sqlalchemy.orm:
        for key in module.__all__:
            if not hasattr(obj, key):
                setattr(obj, key, getattr(module, key))

class SQLAlchemy(object):
    """This class is used to control the SQLAlchemy integration to one
    or more Flask applications. 
    """
    def __init__(self,uri):
        self.engine = create_engine(uri, convert_unicode=True)
        self.session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine))
        self.Base = declarative_base()
        self.Base.query = self.session.query_property()
        _include_sqlalchemy(self)

    def create_all(self):
        """Creates all tables."""
        self.Base.metadata.create_all(bind=self.engine)

    def drop_all(self):
        """Drops all tables."""
        self.Base.metadata.drop_all(bind=self.engine)